package com.example.mq1.mqserver.datacenter;

import com.example.mq1.common.MqException;
import com.example.mq1.mqserver.core.Binding;
import com.example.mq1.mqserver.core.Exchange;
import com.example.mq1.mqserver.core.MSGQueue;
import com.example.mq1.mqserver.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 硬盘数据中心
 * 对文件和数据库进行了统一管理
 */
public class DiskDataCenter {

    //数据库
    private DataBaseManager dataBaseManager = new DataBaseManager();
    //文件
    private MessageFileManager messageFileManager = new MessageFileManager();

    public void init() {
        //数据库进行建库建表的相关操作
        dataBaseManager.init();
        //文件中暂时不需要进行初始化逻辑，但也先加上，后续如果需要也可以加上逻辑
        messageFileManager.init();
    }

    public void insertExchange(Exchange exchange) {
        dataBaseManager.insertExchange(exchange);
    }

    public List<Exchange> selectExchangeAll() {
        return dataBaseManager.selectExchangeAll();
    }

    public void deleteExchange(String exchangeName) {
        dataBaseManager.deleteExchange(exchangeName);
    }

    public void insertQueue(MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
        messageFileManager.createQueueFiles(queue.getQueueName());
    }

    public List<MSGQueue> selectQueueAll() {
        return dataBaseManager.selectQueueAll();
    }

    public void deleteQueue(String queueName) throws IOException, ClassNotFoundException {
        dataBaseManager.deleteQueue(queueName);
        messageFileManager.destroyQueueFile(queueName);
    }

    public void insertBinding(Binding binding) {
        dataBaseManager.insertBinding(binding);
    }

    public List<Binding> selectBindingAll() {
        return dataBaseManager.selectBindingAll();
    }

    public void deleteBinding(Binding binding) {
        dataBaseManager.deleteBinding(binding);
    }

    public void sendMessage(MSGQueue queue, Message message) throws IOException, MqException {
        messageFileManager.sendMessage(queue, message);
    }

    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws IOException, ClassNotFoundException, MqException {
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }

    public void deleteMessage(MSGQueue queue, Message message) throws IOException, ClassNotFoundException, MqException {
        messageFileManager.deleteMessage(queue, message);
        //检查一下是否要触发 gc
        if(messageFileManager.checkGC(queue.getQueueName())) {
            messageFileManager.gc(queue);
        }
    }

}
